//
//  BMSVibrator.m
//  wonderGroMoreDemo
//
//  Created by YeJary on 2025/5/23.
//

// BMSVibrator.m
#import "BMSVibrator.h"
#import <AudioToolbox/AudioToolbox.h>
#import <UIKit/UIKit.h>

@interface BMSVibrator ()
@property (nonatomic, strong) NSTimer *vibrationTimer;
@property (nonatomic, assign) NSInteger currentStep;
@property (nonatomic, strong) NSArray<NSNumber *> *pattern;
@property (nonatomic, assign) NSInteger repeat;
@end

@implementation BMSVibrator

static BMSVibrator *_instance;

+ (instancetype)shared {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[BMSVibrator alloc] init];
    });
    return _instance;
}

+ (void)vibrateOnce {
    if (@available(iOS 10.0, *)) {
        UIImpactFeedbackGenerator *feedback = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleMedium];
        [feedback prepare];
        [feedback impactOccurred];
    } else {
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    }
}

+ (void)vibrateWithPattern:(NSArray<NSNumber *> *)pattern repeat:(NSInteger)repeat {
    if (!pattern || pattern.count == 0) return;

    BMSVibrator *v = [BMSVibrator shared];
    [v.vibrationTimer invalidate];
    v.pattern = pattern;
    v.repeat = repeat;
    v.currentStep = 0;

    [v executeNextStep];
}

- (void)executeNextStep {
    if (self.currentStep >= self.pattern.count) {
        if (self.repeat == 0) {
            self.currentStep = 0;
        } else {
            return;
        }
    }

    NSTimeInterval interval = [self.pattern[self.currentStep] doubleValue] / 1000.0;
    BOOL isVibration = self.currentStep % 2 == 1; // 奇数 index 是震动

    if (isVibration) {
        [BMSVibrator vibrateOnce];
    }

    self.currentStep++;
    self.vibrationTimer = [NSTimer scheduledTimerWithTimeInterval:interval
                                                            target:self
                                                          selector:@selector(executeNextStep)
                                                          userInfo:nil
                                                           repeats:NO];
    [[NSRunLoop mainRunLoop] addTimer:self.vibrationTimer forMode:NSRunLoopCommonModes];
}

+ (void)vibrateCancel {
    [[BMSVibrator shared].vibrationTimer invalidate];
    [BMSVibrator shared].vibrationTimer = nil;
}

@end
